<script lang="ts" setup>
import type {
  GridInstance as VxeGridInstance,
  VxeGridListeners,
  VxeGridProps,
} from '#/adapter/vxe-table';
import type { OrderApi } from '#/api/core/order';

import { computed, onMounted, ref } from 'vue';

import { Button, Form, Input, message, Select } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getOrderListApi } from '#/api/core/order';

// 表格引用
const gridRef = ref<VxeGridInstance>();

// 存储表格数据
const tableData = ref<OrderApi.OrderInfo[]>([]);

// 添加分页相关的 ref
const currentPage = ref(1);
const totalPage = ref(0);

// 表格配置
const gridOptions = computed<VxeGridProps<OrderApi.OrderInfo>>(() => ({
  columns: [
    { field: 'id', title: 'ID',  },
    { field: 'username', title: '用户名',  },
    { field: 'order_no', title: '订单编号', },
    { field: 'transaction_id', title: '微信订单号',  },
    {
      field: 'total_fee',
      title: '金额',
      width: 120,
      formatter: ({ cellValue }) => {
        const amount = Math.max(cellValue, 0);
        return `¥${(amount / 100).toFixed(2)}`;
      },
    },
    { field: 'pay_type', title: '充值方式',  },
    { field: 'pay_status', title: '支付状态',  },
    {
      field: 'body',
      title: '备注',
      showOverflow: {
        type: 'tooltip',
        theme: 'light',
        enterable: true,
        contentStyle: {
          'max-width': '300px',
          'white-space': 'pre-wrap',
        },
      },

    },
    {
      field: 'create_time',
      title: '创建时间',

      formatter: ({ cellValue }) => {
        if (!cellValue) return '';
        return new Date(cellValue).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false,
        });
      },
    },
  ],
  data: tableData.value,
  pagerConfig: {
    enabled: true,
    pageSize: 10,
    total: totalPage.value * 10,
    currentPage: currentPage.value,
    layouts: ['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Total'],
    perfect: true,
  },
  sortConfig: {
    multiple: true,
  },
}));

const gridEvents: VxeGridListeners<OrderApi.OrderInfo> = {
  pageChange: ({ currentPage: newPage }) => {
    currentPage.value = newPage;
    loadData();
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridEvents,
  gridOptions: gridOptions.value,
});

// 定义搜索表单的数据结构
interface SearchForm {
  username: string;
  order_no: string;
  pay_type: string;
  pay_status: number;
}

// 搜索表单数据
const searchForm = ref<SearchForm>({
  username: '',
  order_no: '',
  pay_type: '-1',
  pay_status: -1,
});

// 支付方式选项
const payTypeOptions = [
  { label: '全部', value: '-1' },
  { label: '微信支付', value: '1' },
  { label: '支付宝支付', value: '2' },
];

// 支付状态选项
const payStatusOptions = [
  { label: '全部', value: -1 },
  { label: '未支付', value: 0 },
  { label: '已支付', value: 1 },
];

// 修改加载数据方法
async function loadData() {
  try {
    gridApi.setLoading(true);
    const params = {
      current_page: currentPage.value,
      ...searchForm.value,
    };
    const data = await getOrderListApi(params);

    if (Array.isArray(data) && data.length > 0) {
      tableData.value = data;
      const total_page = data[0]?.total_page || 0;
      totalPage.value = total_page;

      gridApi.setGridOptions({
        data: tableData.value,
        pagerConfig: {
          ...gridOptions.value.pagerConfig,
          total: total_page * 10,
          currentPage: currentPage.value,
        },
      });
    } else {
      tableData.value = [];
    }
  } catch {
    message.error('获取订单列表失败');
    tableData.value = [];
  } finally {
    gridApi.setLoading(false);
  }
}

// 搜索方法
function handleSearch() {
  loadData();
}

// 重置搜索条件
function handleReset() {
  searchForm.value = {
    username: '',
    order_no: '',
    pay_type: '-1',
    pay_status: -1,
  };
  loadData();
}

onMounted(() => {
  loadData();
});

// 表格显示控制
const showBorder = gridApi.useStore((state) => state.gridOptions?.border);
const showStripe = gridApi.useStore((state) => state.gridOptions?.stripe);

function changeBorder() {
  gridApi.setGridOptions({
    border: !showBorder.value,
  });
}

function changeStripe() {
  gridApi.setGridOptions({
    stripe: !showStripe.value,
  });
}
</script>

<template>
  <div class="p-4">
    <!-- 添加搜索表单 -->
    <Form class="mb-4" layout="inline">
      <Form.Item label="用户名">
        <Input
          v-model:value="searchForm.username"
          allow-clear
          placeholder="请输入用户名"
        />
      </Form.Item>
      <Form.Item label="订单号">
        <Input
          v-model:value="searchForm.order_no"
          allow-clear
          placeholder="请输入订单号"
        />
      </Form.Item>
      <Form.Item label="充值方式">
        <Select
          v-model:value="searchForm.pay_type"
          :options="payTypeOptions"
          style="width: 120px"
        />
      </Form.Item>
      <Form.Item label="支付状态">
        <Select
          v-model:value="searchForm.pay_status"
          :options="payStatusOptions"
          style="width: 120px"
        />
      </Form.Item>
      <Form.Item>
        <Button class="mr-2" type="primary" @click="handleSearch">搜索</Button>
        <Button @click="handleReset">重置</Button>
      </Form.Item>
    </Form>

    <div class="vp-raw w-full">
      <Grid ref="gridRef">
        <template #toolbar-tools>
          <Button class="mr-2" type="primary" @click="changeBorder">
            {{ showBorder ? '隐藏' : '显示' }}边框
          </Button>
          <Button class="mr-2" type="primary" @click="changeStripe">
            {{ showStripe ? '隐藏' : '显示' }}斑马纹
          </Button>
        </template>
      </Grid>
    </div>
  </div>
</template>
